/*
 * Created on Feb 20, 2004
 *
 * Author: Sandeep Prakash
 * Project: Sucxentv2 (using leaf nodes only)
 */
package dbsucxentW.storageW.loadersW.relationalW;

import dbsucxentW.storageW.loadersW.XmlShredder;
import dbsucxentW.storageW.parserW.BranchDataSummarizer;
import dbsucxentW.storageW.parserW.BranchOrderDecorator;
import java.io.File;
import java.sql.Connection;
import javax.xml.parsers.SAXParserFactory;


/**
 * @author Administrator
 *
 * 
 */
public class ThreadedRelationalXmlShredder extends XmlShredder {

    private String dataSourceName;
    private SAXParserFactory parserFactory;
    
    public ThreadedRelationalXmlShredder(String file, Connection dbConnection, String dbName) {
        super(file, dbConnection, dbName);
        this.parserFactory = SAXParserFactory.newInstance();
        this.parserFactory.setNamespaceAware(true);
    }

    public ThreadedRelationalXmlShredder(
            String file, 
            Connection dbConnection, 
            String dbName,
            String dataSourceName) {
        super(file, dbConnection, dbName);
        this.dataSourceName = dataSourceName;
        this.parserFactory = SAXParserFactory.newInstance();
        this.parserFactory.setNamespaceAware(true);
    }

    @Override
    public void shred() throws Exception {
        _store = new RelationalStore(_dbConnection, _dbName, this.getFile(), dataSourceName);
        _paths = new PathCollectionRelational(_store, _dbConnection, dataSourceName);

        parse1();
        parse2();
        insert();
    }
    
    private void parse1() throws Exception {
        BranchOrderDecorator _parsing1 = new BranchOrderDecorator();

        javax.xml.parsers.SAXParser parser = this.parserFactory.newSAXParser();
        parser.parse(new File(this.getFile()), _parsing1);

        _summary = _parsing1.getSummary();
        _parsing1 = null;

    }

    /**
     * Second round of parsing
     */
    private void parse2() throws Exception {
        BranchDataSummarizer _parsing2 = new BranchDataSummarizer(_paths, _summary, _store, this.dataSourceName);

        javax.xml.parsers.SAXParser parser = this.parserFactory.newSAXParser();
        parser.parse(new File(this.getFile()), _parsing2);
    }

    /* Same. maybe, move it up the heirarchy - later.
     */
    private void insert() throws Exception {
        _store.store(_summary);
    }
}
